﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml.Linq;
using HandyControl.Controls;
using MyHelper;
using clf.weighing.entity;
using CheckBox = System.Windows.Controls.CheckBox;
using Button = System.Windows.Controls.Button;
using Image = System.Windows.Controls.Image;
using RadioButton = System.Windows.Controls.RadioButton;
using Brushes = System.Windows.Media.Brushes;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;


namespace weighing
{
    /// <summary>
    /// CustomizePrintBillWin.xaml 自定义磅单 的交互逻辑
    /// </summary>
    public partial class CustomizePrintBillWin : GlowWindow
    {
        #region variables
        private Dictionary<string, CheckBox> itemCheckBoxDicts = new Dictionary<string, CheckBox>();
        private Dictionary<string, CheckBox> usedItemCheckBoxDicts = new Dictionary<string, CheckBox>();
        private DragUc? mCurrDragUc;
        private DragLineUc? mCurrLine;
        private double borderWidth = 1;
        private bool isDragging = false;
        private System.Windows.Point mouseOffset;
        private string tempQrcodeValue = "BD2013010500012";
        private string tempBarCodeValue = "201301050001";

        private SysCustomizeBillVo? currCustomizeBillVo;

        private readonly string buyName = "BuyWeighingRb";
        private readonly string SaleName = "SaleWeighingRb";
        private readonly string SelfName = "SelfWeighingRb";
        private readonly string foreginName = "ForeginWeighingRb";
        private readonly string MixturName = "MixtureWeighingRb";
        private readonly string exitSlipName = "ExitSlipRb";
        private readonly string LoadingbillName = "loadingBillRb";
        private readonly string UnLoadingbillName = "UnloadingBillRb";
        /// <summary>
        /// 当前过磅类型的单选按键名称
        /// </summary>
        private string CurrTypeRBName = "";

        /// <summary>
        /// 当前的规则，需要 弹窗 编辑
        /// </summary>
        private QrContentVo CurrQrContentVo
        {
            get
            {
                return currCustomizeBillVo?.QrContentVo ?? new QrContentVo()
                {
                    QrContentType = QrContentType.Number,
                };
            }
            set
            {
                if (currCustomizeBillVo != null) { currCustomizeBillVo.QrContentVo = value; }
            }
        }
        //当前选中的二维码图片
        private Image? currImage = null;
        /// <summary>
        /// 是否是将 存储的值 判定到界面
        /// </summary>
        private bool isBindingValue = false;

        /// <summary>
        /// 是否为首次设置 二维码的内容和规则
        /// </summary>
        private bool isFirstSetQrContent = false;
        #endregion
        public CustomizePrintBillWin()
        {
            InitializeComponent();

            CommonFunction.ShowCustomIcon(this);
        }

        #region window event

        private void GlowWindow_Loaded(object sender, RoutedEventArgs e)
        {
            if (App.Config.WeighingConfig.WeighingMode == WeighingMode.Simple)
            {
                this.BuyWeighingRb.Visibility = Visibility.Collapsed;
                this.SaleWeighingRb.Visibility = Visibility.Collapsed;
                this.SelfWeighingRb.Visibility = Visibility.Collapsed;
                this.ForeginWeighingRb.Visibility = Visibility.Collapsed;
                this.ExitSlipRb.Visibility = Visibility.Collapsed;
                this.MixtureWeighingRb.Visibility = Visibility.Visible;
                this.MixtureWeighingRb.IsChecked = true;
            }
            else
            {
                this.BuyWeighingRb.Visibility = Visibility.Visible;
                this.SaleWeighingRb.Visibility = Visibility.Visible;
                this.SelfWeighingRb.Visibility = Visibility.Visible;
                this.ForeginWeighingRb.Visibility = Visibility.Visible;
                this.ExitSlipRb.Visibility = Visibility.Visible;
                this.MixtureWeighingRb.Visibility = Visibility.Collapsed;
                this.BuyWeighingRb.IsChecked = true;
            }
        }

        private void GlowWindow_Unloaded(object sender, RoutedEventArgs e)
        {

        }

        private void GlowWindow_ContentRendered(object sender, EventArgs e)
        {
            CreateBillItem();

            AddBackFieldItem();
        }

        private void GlowWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {

        }
        private void GlowWindow_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (IsLoaded == false) return;
            //this.fileLv.Width = this.filePanel.ActualHeight;
        }
        #endregion


        #region 创建磅单的选项
        /// <summary>
        /// 创建磅单的选项
        /// </summary>
        private void CreateBillItem()
        {
            Type type = typeof(WeighingBill);

            var fields = type.GetFields().Where((f) =>
            {
                var attr = f.GetCustomAttribute(typeof(WeighingBillAttribute));
                return attr != null;
            });
            var style = FindResource("CheckBoxBaseStyle") as Style;
            itemCheckBoxDicts.Clear();
            this.BillItemSPanel.Children.Clear();
            foreach (var field in fields)
            {
                WeighingBillAttribute? attr = field.GetCustomAttribute(typeof(WeighingBillAttribute)) as WeighingBillAttribute;
                if (attr != null)
                {
                    CheckBox cb = new()
                    {
                        Name = field.Name,
                        Content = attr.Title,
                        ToolTip = attr.MockData,
                        Tag = field.Name,
                        Style = style,
                        IsChecked = false,
                        Margin = new Thickness(4, 2, 4, 2),
                    };

                    cb.Checked += ItemCb_Checked;
                    cb.Unchecked += ItemCb_Unchecked;
                    itemCheckBoxDicts.Add(cb.Name, cb);
                    this.BillItemSPanel.Children.Add(cb);
                }

            }

        }
        /// <summary>
        /// 添加备用字段的选项
        /// </summary>
        private void AddBackFieldItem()
        {
            int type = (int)GetBillType();
            if (type == 0) return;

            List<BackupBillField> fields = BackupBillFieldDao.Instance.SelectAllByType(type);
            var style = FindResource("CheckBoxBaseStyle") as Style;
            this.backFieldItemPanel.Children.Clear();
            foreach (var field in fields)
            {
                if (field.isEnable == 0) continue;
                string name = StringHelper.DBNamingToCamelCase(field.fiedName);
                CheckBox cb = new CheckBox()
                {
                    Name = name,
                    Content = field.displayName,
                    ToolTip = "备用字段",
                    Tag = name,
                    Style = style,
                    IsChecked = false,
                    Margin = new Thickness(4, 2, 4, 2),
                };
                cb.Checked += ItemCb_Checked;
                cb.Unchecked += ItemCb_Unchecked;
                if (itemCheckBoxDicts.Keys.Contains(cb.Name))
                {
                    itemCheckBoxDicts[cb.Name] = cb;
                }
                else
                {
                    itemCheckBoxDicts.Add(cb.Name, cb);
                }
                this.backFieldItemPanel.Children.Add(cb);
            }
        }


        private bool IsExist(string name)
        {
            if (string.IsNullOrEmpty(name)) return false;

            bool res = false;
            for (int i = 0; i < this.mainCanvas.Children.Count; i++)
            {
                var child = this.mainCanvas.Children[i];
                if (child is DragUc uc)
                {
                    if (uc.Name.Equals(name))
                    {
                        res = true;
                        break;
                    }
                }
            }
            return res;
        }

        private void ItemCb_Checked(object sender, RoutedEventArgs e)
        {
            if (currCustomizeBillVo == null)
            {
                var msg = "请先选择一个磅单模板";
                CommonFunction.AlertInfo(msg);
                return;
            }

            CheckBox cb = (CheckBox)sender;

            string name = cb.Name + "Uc";

            if (IsExist(name))
            {
                var msg = "该项已经存在，不能添加。";
                CommonFunction.AlertInfo(msg);
                return;
            }

            var keys = usedItemCheckBoxDicts.Keys;

            if (!keys.Contains(cb.Name))
            {
                usedItemCheckBoxDicts.Add(cb.Name, cb);

                var draguc = new DragUc()
                {
                    Name = name,
                    LabelTitle = cb.Content.ToString(),
                    TextValue = cb.ToolTip?.ToString(),
                    BorderBrush = Brushes.Black,
                    BorderThickness = new Thickness(0),
                };
                draguc.SetTitleText(cb.Content.ToString());
                draguc.SetValueText(cb.ToolTip?.ToString());
                draguc.SetTitleFontSize(14);
                draguc.SetValueFontSize(14);
                draguc.ValueFontSize = 14;
                draguc.TitleFontSize = 14;
                if (cb.Name.StartsWith("billTitle") || cb.Name.StartsWith("billSubTitle"))
                {
                    draguc.ColonsVisibility = Visibility.Collapsed;
                }
                Canvas.SetLeft(draguc, 10.0);
                Canvas.SetTop(draguc, 10.0);

                draguc.MouseLeftButtonUp += Draguc_MouseLeftButtonUp;

                mainCanvas.Children.Add(draguc);
            }
            else
            {
                //已经存在
            }
        }
        private void ItemCb_Unchecked(object sender, RoutedEventArgs e)
        {
            if (currCustomizeBillVo == null)
            {
                var msg = "请先选择一个磅单模板";
                CommonFunction.AlertInfo(msg);
                return;
            }
            CheckBox cb = (CheckBox)sender;
            usedItemCheckBoxDicts.Remove(cb.Name);
            DeleteItem(cb.Name);
        }

        #endregion

        private void StaticText_Click(object sender, RoutedEventArgs e)
        {
            if (currCustomizeBillVo == null)
            {
                var msg = "请先选择一个磅单模板";
                CommonFunction.AlertInfo(msg);
                return;
            }
            Button btn = (Button)sender;
            var draguc = new DragUc()
            {
                //staticText
                Name = btn.Name + "Uc",
                LabelTitle = btn.Content?.ToString(),
                TextValue = btn.ToolTip?.ToString(),
                BorderBrush = Brushes.Black,
                BorderThickness = new Thickness(0),
            };
            if (string.IsNullOrEmpty(draguc.TextValue))
            {
                draguc.TextValue = "固定文本";
            }
            draguc.TitleVisibility = Visibility.Collapsed;
            draguc.ColonsVisibility = Visibility.Collapsed;
            draguc.MouseLeftButtonUp += Draguc_MouseLeftButtonUp;
            Canvas.SetLeft(draguc, 10.0);
            Canvas.SetTop(draguc, 10.0);
            draguc.SetValueFontSize(14);
            draguc.ValueFontSize = 14;
            mainCanvas.Children.Add(draguc);
        }

        private void Draguc_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (sender is DragUc)
            {
                this.mCurrDragUc = sender as DragUc;
                this.currDracUiTb.Text = mCurrDragUc?.LabelTitle;
                this.mCurrLine = null;
                this.widthTb.Text = this.mCurrDragUc?.ActualWidth.ToString();
                this.heightTb.Text = this.mCurrDragUc?.ActualHeight.ToString();
                this.titleFontTb.Text = this.mCurrDragUc?.GetTitleFontSize().ToString();
                this.contentFontTb.Text = this.mCurrDragUc?.GetValueFontSize().ToString();
                this.leftDistanceTb.Text = Canvas.GetLeft(mCurrDragUc).ToString();
                this.topDistanceTb.Text = Canvas.GetTop(mCurrDragUc).ToString();
                this.showTitleCb.IsChecked = this.mCurrDragUc?.TitleVisibility == Visibility.Visible;
                if (mCurrDragUc.Name.StartsWith(Constant.StaticTextNamePre))
                {
                    this.staticTextTb.Visibility = Visibility.Visible;
                    this.staticTextTb.Text = mCurrDragUc.TextValue;
                    this.CopyLineBtn.Visibility = Visibility.Collapsed;
                    this.RefresStaticTextBtn.Visibility = Visibility.Visible;
                    this.CopyStaticTextBtn.Visibility = Visibility.Visible;
                }
                else
                {
                    this.staticTextTb.Visibility = Visibility.Collapsed;
                    this.staticTextTb.Text = String.Empty;
                    if (this.mCurrDragUc.Name.Contains("Vertical") || this.mCurrDragUc.Name.Contains("Horizontal"))
                    {
                        this.CopyLineBtn.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        this.CopyLineBtn.Visibility = Visibility.Collapsed;
                    }

                    this.RefresStaticTextBtn.Visibility = Visibility.Collapsed;
                    this.CopyStaticTextBtn.Visibility = Visibility.Collapsed;
                }
            }
        }

        private void ClearAllStaticText_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < mainCanvas.Children.Count; i++)
            {
                var child = mainCanvas.Children[i];
                DragUc? uc = child as DragUc;
                if (uc != null && uc.Name.StartsWith(Constant.StaticTextNamePre))
                {
                    mainCanvas.Children.Remove(uc);
                }
            }
        }
        /// <summary>
        /// 设置边框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BorderSetBtn_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            if (btn != null && (mCurrDragUc != null || mCurrLine != null))
            {
                string name = btn.Name;

                switch (name)
                {
                    case "allBorderBtn":
                        if (mCurrDragUc != null)
                        {
                            this.mCurrDragUc.BorderThickness = new Thickness(borderWidth);
                        }
                        else if (mCurrLine != null)
                        {
                            if (mCurrLine.Name.Equals(Constant.QrCodeName) || mCurrLine.Name.Equals(Constant.BarCodeName))
                            {
                                this.mCurrLine.MainBorderThickness = new Thickness(borderWidth);
                            }
                        }
                        break;
                    case "noBorderBtn":

                        if (mCurrDragUc != null)
                        {
                            this.mCurrDragUc.BorderThickness = new Thickness(0);
                        }
                        else if (mCurrLine != null)
                        {
                            if (mCurrLine.Name.Equals(Constant.QrCodeName) || mCurrLine.Name.Equals(Constant.BarCodeName))
                            {
                                this.mCurrLine.MainBorderThickness = new Thickness(0);
                            }
                        }
                        break;
                    case "leftBorderBtn":
                        if (mCurrDragUc != null) this.mCurrDragUc.BorderThickness = new Thickness(0, borderWidth, borderWidth, borderWidth);
                        break;
                    case "topBorderBtn":
                        if (mCurrDragUc != null) this.mCurrDragUc.BorderThickness = new Thickness(borderWidth, 0, borderWidth, borderWidth);
                        break;
                    case "righigBorderBtn":
                        if (mCurrDragUc != null) this.mCurrDragUc.BorderThickness = new Thickness(borderWidth, borderWidth, 0, borderWidth);
                        break;
                    case "buttomBorderBtn":
                        if (mCurrDragUc != null) this.mCurrDragUc.BorderThickness = new Thickness(borderWidth, borderWidth, borderWidth, 0);
                        break;
                }
            }
        }

        private void MainCanvas_LostFocus(object sender, RoutedEventArgs e)
        {
            this.mCurrDragUc = null;
            this.mCurrLine = null;
            this.currDracUiTb.Text = "未选择中";
            this.widthTb.Text = String.Empty;
            this.heightTb.Text = String.Empty;
            this.titleFontTb.Text = String.Empty;
            this.contentFontTb.Text = String.Empty;
            this.leftDistanceTb.Text = String.Empty;
            this.topDistanceTb.Text = String.Empty;
        }

        private void WidthTb_LostFocus(object sender, RoutedEventArgs e)
        {
            if (mCurrDragUc != null)
            {
                double w = mCurrDragUc.Width;
                var text = this.widthTb.Text;
                try
                {
                    w = Convert.ToDouble(text);
                }
                catch (Exception)
                {

                }
                mCurrDragUc.Width = w;
            }
            else if (mCurrLine != null && mCurrLine.Tag.ToString().Equals("Horizontal"))
            {
                double w = mCurrLine.ActualWidth;
                var text = this.widthTb.Text;
                try
                {
                    w = Convert.ToDouble(text);
                }
                catch (Exception)
                {

                }
                mCurrLine.Width = w;
                mCurrLine.MainBorderWidth = w;
            }
        }

        private void HeightTb_LostFocus(object sender, RoutedEventArgs e)
        {
            if (mCurrDragUc != null)
            {
                double h = mCurrDragUc.Height;
                var text = this.heightTb.Text;
                try
                {
                    h = Convert.ToDouble(text);
                }
                catch (Exception)
                {

                }
                mCurrDragUc.Height = h;
            }
            else if (mCurrLine != null && mCurrLine.Tag.ToString().Equals("Vertical"))
            {
                double h = mCurrLine.ActualHeight;
                var text = this.heightTb.Text;
                try
                {
                    h = Convert.ToDouble(text);
                }
                catch (Exception)
                {

                }
                mCurrLine.Height = h;
                mCurrLine.MainBorderHeight = h;
                mCurrLine.MainBorder.Height = h;
            }
        }

        private void TitleFontTb_LostFocus(object sender, RoutedEventArgs e)
        {
            if (mCurrDragUc != null)
            {
                double s = mCurrDragUc.TitleFontSize;
                var text = this.titleFontTb.Text;
                try
                {
                    s = Convert.ToDouble(text);
                }
                catch (Exception)
                {

                }
                mCurrDragUc.TitleFontSize = s;
                mCurrDragUc.SetTitleFontSize(s);
            }
        }

        private void ContentFontTb_LostFocus(object sender, RoutedEventArgs e)
        {
            if (mCurrDragUc != null)
            {
                double s = mCurrDragUc.ValueFontSize;
                var text = this.contentFontTb.Text;
                try
                {
                    s = Convert.ToDouble(text);
                }
                catch (Exception)
                {

                }
                mCurrDragUc.ValueFontSize = s;
                mCurrDragUc.SetValueFontSize(s);
            }
        }
        //二维码
        private void QrCodeBorde_Checked(object sender, RoutedEventArgs e)
        {
            if (currCustomizeBillVo == null)
            {
                var msg = "请先选择一个磅单模板";
                CommonFunction.AlertInfo(msg);
                return;
            }

            if (IsAddQrCodeItem())
            {
                CommonFunction.AlertInfo("不能重复添加二维码");
                return;
            }

            DragLineUc line = new()
            {
                Name = Constant.QrCodeName,
                Width = 120,
                Height = 120,
                Tag = Constant.QrCodeName,
            };
            line.MainBorderWidth = line.Width;
            line.MainBorderHeight = line.Height;
            line.MainBorderThickness = new Thickness(0);
            line.SetValue(Canvas.TopProperty, 10.0);
            line.SetValue(Canvas.LeftProperty, 10.0);
            var image = new Image()
            {
                Name = "QrCodeImage",
            };
            line.MainBorder.Child = image;
            CommonFunction.ShowBillNumberQrCode(image, tempQrcodeValue);
            line.MouseLeftButtonUp += Line_MouseLeftButtonUp;
            this.mainCanvas.Children.Add(line);
        }

        private void QrCodeBorde_Unchecked(object sender, RoutedEventArgs e)
        {
            DeleteItem(Constant.QrCodeName);
        }
        //条码
        private void LineCodeBorde_Checked(object sender, RoutedEventArgs e)
        {
            if (IsAddBarCodeItem())
            {
                CommonFunction.AlertInfo("不能重复添加条形码");
                return;
            }
            DragLineUc line = new DragLineUc
            {
                Name = Constant.BarCodeName,
                Width = 100,
                Height = 40,
                Tag = Constant.BarCodeName,
            };
            line.MainBorder.Width = line.Width;
            line.MainBorder.Height = line.Height;
            line.MainBorderHeight = line.Height;
            line.MainBorder.BorderThickness = new Thickness(0);
            line.MainBorderThickness = new Thickness(0);
            line.MainBorder.Padding = new Thickness(1);
            line.SetValue(Canvas.TopProperty, 10.0);
            line.SetValue(Canvas.LeftProperty, 10.0);

            line.MainBorder.Child = null;
            var image = new Image()
            {
                Name = "LineCodeImage",
                Source = null,
            };
            line.MainBorder.Child = image;
            CommonFunction.ShowBillNumberBarCode(image, tempBarCodeValue);
            line.MouseLeftButtonUp += Line_MouseLeftButtonUp;
            this.mainCanvas.Children.Add(line);
        }

        private void LineCodeBorde_Unchecked(object sender, RoutedEventArgs e)
        {
            DeleteItem(Constant.BarCodeName);
        }

        private void HorizontallineBtn_Click(object sender, RoutedEventArgs e)
        {
            if (currCustomizeBillVo == null)
            {
                var msg = "请先选择一个磅单模板";
                CommonFunction.AlertInfo(msg);
                return;
            }

            var horizontalLine = CreateLine(true);

            this.mainCanvas.Children.Add(horizontalLine);
        }


        private DragLineUc CreateLine(bool isHorizontal = true, double width = 0, double height = 0)
        {
            string tag = "";
            if (isHorizontal)
            {
                tag = "Horizontal";
                if (width == 0) width = 660;
                if (height == 0) height = 5;
            }
            else
            {
                if (width == 0) width = 5;
                if (height == 0) height = 180;
                tag = "Vertical";
            }

            DragLineUc line = new()
            {
                Width = width,
                Height = height,
                Tag = tag,
            };
            line.MainBorderWidth = line.Width;
            line.MainBorderHeight = line.Height;
            if (isHorizontal)
            {
                line.MainBorderThickness = new Thickness(0, 1, 0, 0);
            }
            else
            {
                line.MainBorderThickness = new Thickness(1, 0, 0, 0);
            }

            line.SetValue(Canvas.TopProperty, 10.0);
            line.SetValue(Canvas.LeftProperty, 10.0);

            line.MouseLeftButtonUp += Line_MouseLeftButtonUp;

            return line;
        }

        private void Line_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            DragLineUc? lineUc = sender as DragLineUc;
            if (lineUc != null)
            {
                mCurrDragUc = null;
                this.MainCanvas_LostFocus(sender, e);
                mCurrLine = lineUc;

                this.staticTextTb.Visibility = Visibility.Collapsed;
                this.RefresStaticTextBtn.Visibility = Visibility.Collapsed;
                this.CopyStaticTextBtn.Visibility = Visibility.Collapsed;

                if (lineUc.Name.Equals(Constant.QrCodeName))
                {
                    this.currDracUiTb.Text = "二维码";
                    Border? border = lineUc.Content as Border;
                    this.heightTb.Text = lineUc.ActualHeight + "";
                    currImage = border?.Child as Image;
                    ShowQrOptions(true);
                }
                else if (lineUc.Name.Equals(Constant.BarCodeName))
                {
                    this.currDracUiTb.Text = "条形码";
                    this.heightTb.Text = lineUc.ActualHeight + "";
                    currImage = null;
                }
                else
                {
                    this.CopyLineBtn.Visibility = Visibility.Visible;
                    string t;
                    if (lineUc.Tag.ToString().Equals("Vertical"))
                    {
                        t = "垂直";
                    }
                    else
                    {
                        t = "水平";
                    }
                    this.currDracUiTb.Text = t + "线条";
                }

                if (lineUc != null && lineUc.Tag.ToString().Equals("Vertical"))
                {
                    this.heightTb.Text = lineUc.ActualHeight + "";
                }
                else
                {
                    this.widthTb.Text = lineUc?.ActualWidth + "";
                }
                this.leftDistanceTb.Text = Canvas.GetLeft(mCurrLine).ToString();
                this.topDistanceTb.Text = Canvas.GetTop(mCurrLine).ToString();
            }
        }

        private void VerticallineBtn_Click(object sender, RoutedEventArgs e)
        {
            if (currCustomizeBillVo == null)
            {
                var msg = "请先选择一个磅单模板";
                CommonFunction.AlertInfo(msg);
                return;
            }
            var verticalLine = CreateLine(false);

            mainCanvas.Children.Add(verticalLine);
        }

        private void DelCurrBtn_Click(object sender, RoutedEventArgs e)
        {
            DeleteItem();
        }

        private void DeleteItem(string partName = null)
        {
            if (string.IsNullOrEmpty(partName))
            {
                if (mCurrDragUc != null)
                {
                    this.mainCanvas.Children.Remove(mCurrDragUc);
                    mCurrDragUc = null;
                    MainCanvas_LostFocus(null, null);
                }
                else if (mCurrLine != null)
                {
                    this.mainCanvas.Children.Remove(mCurrLine);
                    mCurrLine = null;
                    this.widthTb.Text = String.Empty;
                    this.heightTb.Text = String.Empty;
                }
            }
            else
            {
                string name;
                if (partName.EndsWith("Uc"))
                {
                    name = partName;
                }
                else
                {
                    name = partName + "Uc";
                }
                for (int i = 0; i < this.mainCanvas.Children.Count; i++)
                {
                    var child = this.mainCanvas.Children[i];
                    if (child is DragUc uc)
                    {
                        if (uc.Name.Equals(name))
                        {
                            this.mainCanvas.Children.Remove(uc);
                        }
                    }

                    if (child is DragLineUc lineUc)
                    {
                        if (lineUc.Name.Equals(name))
                        {
                            this.mainCanvas.Children.Remove(lineUc);
                        }
                    }
                }

            }
        }

        private void ClearConvasChilds()
        {
            this.mainCanvas.Children.Clear();
            if (this.mainCanvas.Children.Count > 0)
            {
                this.mainCanvas.Children.Clear();
            }

        }

        private void StaticTextTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (mCurrDragUc != null && this.staticTextTb.IsVisible == true)
            {
                mCurrDragUc.SetValueText(this.staticTextTb.Text);
                mCurrDragUc.TextValue = this.staticTextTb.Text;
            }
        }
        #region show or hide title and content
        private void ShowTitleCb_Checked(object sender, RoutedEventArgs e)
        {
            if (mCurrDragUc != null)
            {
                mCurrDragUc.TitleVisibility = Visibility.Visible;
                mCurrDragUc.SetTitleVisable(true);
            }
        }

        private void ShowTitleCb_Unchecked(object sender, RoutedEventArgs e)
        {
            if (mCurrDragUc != null)
            {
                mCurrDragUc.TitleVisibility = Visibility.Collapsed;
                mCurrDragUc.SetTitleVisable(false);
            }
        }

        private void ShowContentCb_Checked(object sender, RoutedEventArgs e)
        {
            if (mCurrDragUc != null)
            {
                mCurrDragUc.VallueVisibility = Visibility.Visible;
                mCurrDragUc.SetValueVisable(true);
            }
        }

        private void ShowContentCb_Unchecked(object sender, RoutedEventArgs e)
        {
            if (mCurrDragUc != null)
            {
                mCurrDragUc.VallueVisibility = Visibility.Collapsed;
                mCurrDragUc.SetValueVisable(false);
            }
        }
        #endregion
        //距左
        private void LeftDistanceTb_LostFocus(object sender, RoutedEventArgs e)
        {
            if (mCurrDragUc != null)
            {
                double t = Canvas.GetLeft(mCurrDragUc);
                try
                {
                    var text = this.leftDistanceTb.Text?.Trim();
                    t = Convert.ToDouble(text);
                }
                catch (Exception)
                {
                    throw;
                }
                Canvas.SetLeft(mCurrDragUc, t);

            }
            else if (mCurrLine != null)
            {
                double t = Canvas.GetLeft(mCurrLine);
                try
                {
                    var text = this.leftDistanceTb.Text?.Trim();
                    t = Convert.ToDouble(text);
                }
                catch (Exception)
                {

                }
                Canvas.SetLeft(mCurrLine, t);
            }

        }
        //距顶
        private void TopDistanceTb_LostFocus(object sender, RoutedEventArgs e)
        {
            if (mCurrDragUc != null)
            {
                double t = Canvas.GetTop(mCurrDragUc);
                try
                {
                    var text = this.topDistanceTb.Text?.Trim();
                    t = Convert.ToDouble(text);
                }
                catch (Exception)
                {
                    throw;
                }
                Canvas.SetTop(mCurrDragUc, t);

            }
            else if (mCurrLine != null)
            {
                double t = Canvas.GetTop(mCurrLine);
                try
                {
                    var text = this.topDistanceTb.Text?.Trim();
                    t = Convert.ToDouble(text);
                }
                catch (Exception)
                {
                    throw;
                }
                Canvas.SetTop(mCurrLine, t);
            }
        }


        private bool IsAddQrCodeItem()
        {
            bool res = false;
            for (int i = 0; i < this.mainCanvas.Children.Count; i++)
            {
                var child = this.mainCanvas.Children[i];
                if (child is DragLineUc lineUc)
                {
                    if (lineUc.Name.Equals(Constant.QrCodeName))
                    {
                        res = true;
                        break;
                    }
                }
            }
            return res;
        }


        private bool IsAddBarCodeItem()
        {
            bool res = false;
            for (int i = 0; i < this.mainCanvas.Children.Count; i++)
            {
                var child = this.mainCanvas.Children[i];
                if (child is DragLineUc lineUc)
                {
                    if (lineUc.Name.Equals(Constant.BarCodeName))
                    {
                        res = true;
                        break;
                    }
                }
            }
            return res;
        }

        #region Radio button changed .type changed

        //过磅类型
        private void WeighingTypeRb_Checked(object sender, RoutedEventArgs e)
        {
            if (sender is RadioButton rb)
            {
                ChangeBillType(rb.Name);
            }
        }

        /// <summary>
        /// 出门条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExitSlipRb_Checked(object sender, RoutedEventArgs e)
        {
            if (sender is RadioButton rb)
            {
                ChangeBillType(rb.Name);
            }
        }

        /// <summary>
        /// 装货单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadingBillRb_Checked(object sender, RoutedEventArgs e)
        {
            if (sender is RadioButton rb)
            {
                ChangeBillType(rb.Name);
            }
        }

        /// <summary>
        /// 卸货单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UnloadingBillRb_Checked(object sender, RoutedEventArgs e)
        {
            if (sender is RadioButton rb)
            {
                ChangeBillType(rb.Name);
            }
        }

        private void ChangeBillType(string name)
        {
            if (!IsLoaded) return;
            CurrTypeRBName = name;
            mCurrDragUc = null;
            mCurrLine = null;
            currCustomizeBillVo = null;
            ClearConvasChilds();
            MainCanvas_LostFocus(null, null);
            this.fileNameTb.Text = String.Empty;
            this.addCusBillbtn.Visibility = Visibility.Visible;
            this.CancelEditCusBillbtn.Visibility = Visibility.Collapsed;

            LoadFileItemSource(name);

            AddBackFieldItem();
        }

        #endregion

        private void LoadFileItemSource(string name = "")
        {
            if (string.IsNullOrEmpty(name))
            {
                if (this.BuyWeighingRb.IsChecked == true)
                {
                    name = this.BuyWeighingRb.Name;
                }
                else if (this.SaleWeighingRb.IsChecked == true)
                {
                    name = this.SaleWeighingRb.Name; ;
                }
                else if (this.SelfWeighingRb.IsChecked == true)
                {
                    name = this.SelfWeighingRb.Name; ;
                }
                else if (this.ForeginWeighingRb.IsChecked == true)
                {
                    name = this.ForeginWeighingRb.Name;
                }
                else if (this.MixtureWeighingRb.IsChecked == true)
                {
                    name = this.MixtureWeighingRb.Name;
                }
                else if (this.ExitSlipRb.IsChecked == true)
                {
                    name = this.ExitSlipRb.Name;
                }
                else if (this.loadingBillRb.IsChecked == true)
                {
                    name = this.loadingBillRb.Name;
                }
                else if (this.UnloadingBillRb.IsChecked == true)
                {
                    name = this.UnloadingBillRb.Name;
                }
            }

            WeightingBillType type = GetBillType();

            if (type == WeightingBillType.UNKNOWN)
            {
                CommonFunction.AlertInfo("选择磅单类型");
                return;
            }

            var customizeBills = SysCustomizeBillDao.Instance.SelectByBillType(type);

            var itemsSource = customizeBills.Select((i) =>
                {
                    return new SysCustomizeBillVo(i);
                }).ToList();
            this.fileLv.ItemsSource = null;
            this.fileLv.ItemsSource = itemsSource;
            if (itemsSource == null || itemsSource.Count == 0)
            {
                var text = GetChedkedRadioContent() + "模板01";
                this.fileNameTb.Text = text;
            }
        }

        //修改
        private void EditBtn_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button btn)
            {
                if (btn.Tag is SysCustomizeBillVo billVo)
                {
                    currCustomizeBillVo = billVo;
                    this.addCusBillbtn.Visibility = Visibility.Collapsed;
                    BuildAndShowConvasChilds();
                    this.CancelEditCusBillbtn.Visibility = Visibility.Visible;
                    this.fileNameTb.Text = billVo.Name;
                }
            }
        }

        private void BuildAndShowConvasChilds()
        {
            mCurrDragUc = null;
            mCurrLine = null;
            ClearConvasChilds();
            MainCanvas_LostFocus(null, null);
            if (currCustomizeBillVo != null)
            {
                var content = currCustomizeBillVo.Content;
                if (string.IsNullOrEmpty(content))
                {
                    return;
                }
                List<string> nodes = JsonHelper.JsonToObject<List<string>>(content);
                if (nodes == null || nodes.Count <= 0)
                {
                    var msg = "可以之前没有增加任何内容，请现在增加。";
                    CommonFunction.AlertInfo(msg);
                    return;
                }

                // start build 
                for (int i = 0; i < nodes.Count; i++)
                {
                    string itemXaml = nodes[i];
                    string decodeXaml = UrlHelper.Decode(itemXaml);

                    var ui = XamlReader.Parse(decodeXaml);

                    if (ui is DragUc uc)
                    {
                        uc.MouseLeftButtonUp += Draguc_MouseLeftButtonUp;
                        this.mainCanvas.Children.Add(uc);
                    }
                    else if (ui is DragLineUc lineUc)
                    {
                        if (lineUc.Name.Equals(Constant.QrCodeName) || lineUc.Name.Equals(Constant.BarCodeName))
                        {
                            Border? border = lineUc.Content as Border;
                            Image? img = border?.Child as Image;
                            ShowImageSourceAsync(img, lineUc.Name);
                        }

                        lineUc.MouseLeftButtonUp += Line_MouseLeftButtonUp;
                        this.mainCanvas.Children.Add(lineUc);
                    }
                    else
                    {
                        //不支持的类型
                    }
                }
            }          
        }

        private void ShowImageSourceAsync(Image? image, string name)
        {
            Task.Delay(1000).ContinueWith((t) =>
            {
                this.Dispatcher.Invoke(() =>
                {
                    if (name.Equals(Constant.QrCodeName))
                    {
                        CommonFunction.ShowBillNumberQrCode(image, tempQrcodeValue);
                    }
                    else
                    {
                        CommonFunction.ShowBillNumberBarCode(image, tempBarCodeValue);
                    }
                });
            });
        }

        //删除
        private void DelBtn_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button btn)
            {
                if (btn.Tag is SysCustomizeBillVo billVo)
                {
                    var msg = $"是否要删除名称为 {billVo.Name} 的磅单";
                    var result = CommonFunction.Ask(msg);
                    if (result == MessageBoxResult.Yes)
                    {
                        int res = SysCustomizeBillDao.Instance.Sqlite.Delete(billVo.mCustomizeBill);
                        if (res > 0)
                        {
                            if (currCustomizeBillVo != null && currCustomizeBillVo.Id == billVo.Id)
                            {
                                currCustomizeBillVo = null;
                            }
                            CommonFunction.AlertInfo("删除成功");
                            LoadFileItemSource();
                        }
                        else
                        {
                            CommonFunction.AlertInfo("删除失败");
                        }
                    }
                }
            }
        }

        //添加
        private void AddCusBillbtn_Click(object sender, RoutedEventArgs e)
        {
            var type = GetBillType();
            if (type == WeightingBillType.UNKNOWN)
            {
                CommonFunction.AlertInfo("请选择磅单类型");
                return;
            }
            string name = this.fileNameTb.Text;
            if (string.IsNullOrEmpty(name) || name.Length < 3)
            {
                CommonFunction.AlertInfo("磅单名称长度不能小3位");
                return;
            }
            CustomizeBill? bill = SysCustomizeBillDao.Instance.FindByNameAndType(name, type);
            if (bill != null)
            {
                var m = type == WeightingBillType.ExitSlip ? "出门条" : "磅单";
                CommonFunction.AlertInfo(m + " ：" + name + "已经存在");
                return;
            }
            string content = GetConvasChildsXaml();
            var newBill = new CustomizeBill()
            {
                id = IdHelper.LongID,
                name = name,
                type = (int)type,
                content = content,
                isUsed = false,
                companyId = App.CurrentCompanyVo?.Id ?? 0,
                addTime = DateTime.Now,
            };

            int res = SysCustomizeBillDao.Instance.Insert(newBill);

            if (res > 0)
            {
                CommonFunction.AlertInfo("添加成功");
                this.fileNameTb.Text = String.Empty;
                LoadFileItemSource();
            }
            else
            {
                CommonFunction.AlertInfo("添加失败");
            }
        }

        //保存
        private void SaveCusBillbtn_Click(object sender, RoutedEventArgs e)
        {
            if (currCustomizeBillVo != null)
            {
                if (this.fileNameTb.Text.Trim() != currCustomizeBillVo.Name)
                {
                    currCustomizeBillVo.Name = this.fileNameTb.Text.Trim();
                }

                var xaml = GetConvasChildsXaml();
                currCustomizeBillVo.Content = xaml;

                currCustomizeBillVo.PrintWidth = GetPrintWidth() + 10;
                currCustomizeBillVo.PrintHeight = GetPrintHeight() + 10;
    
                currCustomizeBillVo.QrContentVo = CurrQrContentVo;

                currCustomizeBillVo.UpdateTime = DateTime.Now;

                int res = SysCustomizeBillDao.Instance.Update(currCustomizeBillVo.mCustomizeBill);

                if (res > 0)
                {
                    CommonFunction.AlertInfo("保存成功");
                    this.CancelEditCusBillbtn.Visibility = Visibility.Collapsed;
                }
                else
                {
                    CommonFunction.AlertInfo("保存失败");
                }
            }
        }


        private WeightingBillType GetBillType()
        {
            WeightingBillType type;
            if (this.BuyWeighingRb.IsChecked == true)
            {
                type = WeightingBillType.Buy;
            }
            else if (this.SaleWeighingRb.IsChecked == true)
            {
                type = WeightingBillType.Sale;
            }
            else if (this.SelfWeighingRb.IsChecked == true)
            {
                type = WeightingBillType.Self;
            }
            else if (this.ForeginWeighingRb.IsChecked == true)
            {
                type = WeightingBillType.Foreign;
            }
            else if (this.ExitSlipRb.IsChecked == true)
            {
                type = WeightingBillType.ExitSlip;
            }
            else if (this.MixtureWeighingRb.IsChecked == true)
            {
                type = WeightingBillType.Mixture;
            }
            else if (this.UnloadingBillRb.IsChecked == true)
            {
                type = WeightingBillType.UnLoadingBill;
            }
            else if (this.loadingBillRb.IsChecked == true)
            {
                type = WeightingBillType.LoadingBill;
            }
            else
            {
                type = WeightingBillType.UNKNOWN;
            }
            return type;
        }

        private string GetChedkedRadioContent()
        {
            string content;
            if (this.BuyWeighingRb.IsChecked == true)
            {
                content = this.BuyWeighingRb.Content.ToString();
            }
            else if (this.SaleWeighingRb.IsChecked == true)
            {
                content = this.SaleWeighingRb.Content.ToString();
            }
            else if (this.SelfWeighingRb.IsChecked == true)
            {
                content = this.SelfWeighingRb.Content.ToString();
            }
            else if (this.ForeginWeighingRb.IsChecked == true)
            {
                content = this.ForeginWeighingRb.Content.ToString();
            }
            else if (this.ExitSlipRb.IsChecked == true)
            {
                content = this.ExitSlipRb.Content.ToString();
            }
            else if (this.MixtureWeighingRb.IsChecked == true)
            {
                content = this.MixtureWeighingRb.Content.ToString();
            }
            else if (this.UnloadingBillRb.IsChecked == true)
            {
                content = this.UnloadingBillRb.Content.ToString();
            }
            else if (this.loadingBillRb.IsChecked == true)
            {
                content = this.loadingBillRb.Content.ToString();
            }
            else
            {
                content = "未知";
            }
            return content;
        }


        private string GetConvasChildsXaml()
        {
            List<string> nodes = new List<string>();

            for (int i = 0; i < mainCanvas.Children.Count; i++)
            {
                var child = (ContentControl)mainCanvas.Children[i];
                //保存时清空   image.Source
                Image image = null;
                if (child.Name.EndsWith(Constant.QrCodeName) || child.Name.EndsWith(Constant.BarCodeName))
                {
                    Border border = child.Content as Border;
                    if (border != null)
                    {
                        image = border.Child as Image;
                        image.Source = null;
                    }
                }
                string xaml = XamlWriter.Save(child);
                //show image 
                if (child.Name.EndsWith(Constant.QrCodeName))
                {
                    CommonFunction.ShowBillNumberQrCode(image, tempQrcodeValue);
                }
                else if (child.Name.EndsWith(Constant.BarCodeName))
                {
                    CommonFunction.ShowBillNumberBarCode(image, tempBarCodeValue);
                }
                var encodeXaml = UrlHelper.Encode(xaml);
                nodes.Add(encodeXaml);
            }
            var json = JsonHelper.ObjectToJson(nodes);
            return json;
        }

        //取消
        private void CancelEditCusBillbtn_Click(object sender, RoutedEventArgs e)
        {
            this.currCustomizeBillVo = null;
            mCurrDragUc = null;
            mCurrLine = null;
            BuildAndShowConvasChilds();
            MainCanvas_LostFocus(null, e);
            this.addCusBillbtn.Visibility = Visibility.Visible;
            this.CancelEditCusBillbtn.Visibility = Visibility.Collapsed;
        }
        // TODO 打印测试
        private void PrintTestBillbtn_Click(object sender, RoutedEventArgs e)
        {

        }

        private double GetPrintWidth()
        {
            ContentControl? uc;
            double left = 0;
            double w = 0;
            for (int i = 0; i < this.mainCanvas.Children.Count; i++)
            {
                var child = this.mainCanvas.Children[i];
                uc = child as ContentControl;

                if (uc != null)
                {
                    var l = Canvas.GetLeft(uc);
                    if (l > left)
                    {
                        left = l;
                        w = l + uc.ActualWidth;
                    }
                }
            }
            return w;
        }

        private double GetPrintHeight()
        {
            ContentControl uc;
            double top = 0;
            double h = 0;
            for (int i = 0; i < this.mainCanvas.Children.Count; i++)
            {
                var child = this.mainCanvas.Children[i];
                uc = child as ContentControl;

                if (uc != null)
                {
                    var t = Canvas.GetTop(uc);
                    if (t > top)
                    {
                        top = t;
                        h = t + uc.ActualHeight;
                    }
                }
            }
            return h;
        }
        //使用
        private void UseBtn_Click(object sender, RoutedEventArgs e)
        {
            Button? button = sender as Button;
            if (button?.Tag is SysCustomizeBillVo vo)
            {
                if (vo.IsUsed == true)
                {
                    var m = $" 是否要取消 {vo.Name}的使用 ";
                    var result = CommonFunction.Ask(m);
                    if (result == MessageBoxResult.Yes)
                    {
                        var cb = vo.mCustomizeBill;
                        cb.isUsed = false;
                        cb.addTime = DateTime.Now;
                        int res = SysCustomizeBillDao.Instance.Update(cb);
                        if (res > 0)
                        {
                            CommonFunction.AlertInfo("操作成功。");
                            LoadFileItemSource();
                        }
                        else
                        {
                            CommonFunction.AlertInfo("操作失败。");
                        }
                    }
                }
                else
                {
                    var msg = $"是否要使用 {vo.Name} 打印模板";
                    var result = CommonFunction.Ask(msg);
                    if (result == MessageBoxResult.Yes)
                    {
                        var cb = vo.mCustomizeBill;
                        cb.isUsed = true;
                        cb.addTime = DateTime.Now;
                        int res = SysCustomizeBillDao.Instance.UseingCustomer(cb);
                        if (res > 0)
                        {
                            CommonFunction.AlertInfo("操作成功。");
                            LoadFileItemSource();
                        }
                        else
                        {
                            CommonFunction.AlertInfo("操作失败。");
                        }
                    }
                }

            }
        }


        #region copy to

        private SysCustomizeBillVo customizeBillVo;

        private void CopyToBtn_Click(object sender, RoutedEventArgs e)
        {
            this.copyToPopup.IsOpen = !this.copyToPopup.IsOpen;

            if (this.copyToPopup.IsOpen == true)
            {
                var btn = sender as Button;
                var bill = btn?.Tag as SysCustomizeBillVo;
                customizeBillVo = bill;
            }
            else
            {
                customizeBillVo = null;
            }
        }


        private void CopyToPopup_Closed(object sender, EventArgs e)
        {
            customizeBillVo = null;
        }
        private void SaveCopyPopupBtn_Click(object sender, RoutedEventArgs e)
        {
            string name = this.copyNameTb.Text;
            if (name.Length < 5)
            {
                var msg = "请输入一个5个字以上的模板名称";
                CommonFunction.AlertInfo(msg);
                this.copyNameTb.Focus();
                return;
            }
            var customize = customizeBillVo.mCustomizeBill;
            customize.id += IdHelper.LongID;
            customize.name = name;
            customize.addTime = DateTime.Now;
            customize.isUsed = false;

            int res = SysCustomizeBillDao.Instance.Insert(customize);

            if (res > 0)
            {
                var msg = "复制成功";
                CommonFunction.AlertInfo(msg);
                this.copyToPopup.IsOpen = false;
                LoadFileItemSource();
            }
            else
            {
                var msg = "复制失败";
                CommonFunction.AlertInfo(msg);
            }
        }

        private void CopyPopupCancelBtn_Click(object sender, RoutedEventArgs e)
        {
            this.copyNameTb.Text = String.Empty;
            this.copyToPopup.IsOpen = false;
        }


        #endregion

        #region move

        private void MoveToBtn_Click(object sender, RoutedEventArgs e)
        {
            this.moveToPopup.IsOpen = !this.moveToPopup.IsOpen;

            if (this.moveToPopup.IsOpen == true)
            {
                var btn = sender as Button;
                var vo = btn?.Tag as SysCustomizeBillVo;
                customizeBillVo = vo;

                switch (customizeBillVo?.Type ?? 0)
                {
                    case (int)WeightingBillType.Buy:
                        this.BuyFolderBillRb.Visibility = Visibility.Collapsed;
                        this.SaleFolderBillRb.Visibility = Visibility.Visible;
                        this.SelfFolderBillRb.Visibility = Visibility.Visible;
                        this.ForeginFolderBillRb.Visibility = Visibility.Visible;
                        this.ExitFolderBillRb.Visibility = Visibility.Visible;
                        this.MixtrueFolderBillRb.Visibility = Visibility.Visible;
                        this.LoadBillRb.Visibility = Visibility.Visible;
                        this.UnLoadBillRb.Visibility = Visibility.Visible;
                        break;
                    case (int)WeightingBillType.Sale:
                        this.BuyFolderBillRb.Visibility = Visibility.Visible;
                        this.SaleFolderBillRb.Visibility = Visibility.Collapsed;
                        this.SelfFolderBillRb.Visibility = Visibility.Visible;
                        this.ForeginFolderBillRb.Visibility = Visibility.Visible;
                        this.ExitFolderBillRb.Visibility = Visibility.Visible;
                        this.MixtrueFolderBillRb.Visibility = Visibility.Visible;
                        this.LoadBillRb.Visibility = Visibility.Visible;
                        this.UnLoadBillRb.Visibility = Visibility.Visible;
                        break;
                    case (int)WeightingBillType.Self:
                        this.BuyFolderBillRb.Visibility = Visibility.Visible;
                        this.SaleFolderBillRb.Visibility = Visibility.Visible;
                        this.SelfFolderBillRb.Visibility = Visibility.Collapsed;
                        this.ForeginFolderBillRb.Visibility = Visibility.Visible;
                        this.ExitFolderBillRb.Visibility = Visibility.Visible;
                        this.MixtrueFolderBillRb.Visibility = Visibility.Visible;
                        this.LoadBillRb.Visibility = Visibility.Visible;
                        this.UnLoadBillRb.Visibility = Visibility.Visible;
                        break;
                    case (int)WeightingBillType.Foreign:
                        this.BuyFolderBillRb.Visibility = Visibility.Visible;
                        this.SaleFolderBillRb.Visibility = Visibility.Visible;
                        this.SelfFolderBillRb.Visibility = Visibility.Visible;
                        this.ForeginFolderBillRb.Visibility = Visibility.Collapsed;
                        this.ExitFolderBillRb.Visibility = Visibility.Visible;
                        this.MixtrueFolderBillRb.Visibility = Visibility.Visible;
                        this.LoadBillRb.Visibility = Visibility.Visible;
                        this.UnLoadBillRb.Visibility = Visibility.Visible;
                        break;
                    case (int)WeightingBillType.Mixture:
                        this.BuyFolderBillRb.Visibility = Visibility.Visible;
                        this.SaleFolderBillRb.Visibility = Visibility.Visible;
                        this.SelfFolderBillRb.Visibility = Visibility.Visible;
                        this.ForeginFolderBillRb.Visibility = Visibility.Visible;
                        this.ExitFolderBillRb.Visibility = Visibility.Visible;
                        this.MixtrueFolderBillRb.Visibility = Visibility.Collapsed;
                        this.LoadBillRb.Visibility = Visibility.Visible;
                        this.UnLoadBillRb.Visibility = Visibility.Visible;
                        break;
                    case (int)WeightingBillType.ExitSlip:
                        this.BuyFolderBillRb.Visibility = Visibility.Visible;
                        this.SaleFolderBillRb.Visibility = Visibility.Visible;
                        this.SelfFolderBillRb.Visibility = Visibility.Visible;
                        this.ForeginFolderBillRb.Visibility = Visibility.Visible;
                        this.ExitFolderBillRb.Visibility = Visibility.Collapsed;
                        this.MixtrueFolderBillRb.Visibility = Visibility.Visible;
                        this.LoadBillRb.Visibility = Visibility.Visible;
                        this.UnLoadBillRb.Visibility = Visibility.Visible;
                        break;
                    case (int)WeightingBillType.LoadingBill:
                        this.BuyFolderBillRb.Visibility = Visibility.Visible;
                        this.SaleFolderBillRb.Visibility = Visibility.Visible;
                        this.SelfFolderBillRb.Visibility = Visibility.Visible;
                        this.ForeginFolderBillRb.Visibility = Visibility.Visible;
                        this.ExitFolderBillRb.Visibility = Visibility.Visible;
                        this.MixtrueFolderBillRb.Visibility = Visibility.Visible;
                        this.LoadBillRb.Visibility = Visibility.Collapsed;
                        this.UnLoadBillRb.Visibility = Visibility.Visible;
                        break;
                    case (int)WeightingBillType.UnLoadingBill:
                        this.BuyFolderBillRb.Visibility = Visibility.Visible;
                        this.SaleFolderBillRb.Visibility = Visibility.Visible;
                        this.SelfFolderBillRb.Visibility = Visibility.Visible;
                        this.ForeginFolderBillRb.Visibility = Visibility.Visible;
                        this.ExitFolderBillRb.Visibility = Visibility.Visible;
                        this.MixtrueFolderBillRb.Visibility = Visibility.Visible;
                        this.LoadBillRb.Visibility = Visibility.Visible;
                        this.UnLoadBillRb.Visibility = Visibility.Collapsed;
                        break;
                }
            }
            else
            {
                customizeBillVo = null;
            }
        }



        private void MoveToPopup_Closed(object sender, EventArgs e)
        {
            this.BuyFolderBillRb.IsChecked = false;
            this.SaleFolderBillRb.IsChecked = false;
            this.SelfFolderBillRb.IsChecked = false;
            this.ForeginFolderBillRb.IsChecked = false;
            this.SelfFolderBillRb.IsChecked = false;
            this.ExitFolderBillRb.IsChecked = false;
            this.MixtrueFolderBillRb.IsChecked = false;
            this.LoadBillRb.IsChecked = false;
            this.UnLoadBillRb.IsChecked = false;
        }

        private void SaveMovePopupBtn_Click(object sender, RoutedEventArgs e)
        {
            int type = 0;

            if (this.BuyFolderBillRb.IsChecked == true)
            {
                type = (int)WeightingBillType.Buy;
            }
            if (this.SaleFolderBillRb.IsChecked == true)
            {
                type = (int)WeightingBillType.Sale;
            }

            if (this.SelfFolderBillRb.IsChecked == true)
            {
                type = (int)WeightingBillType.Self;
            }

            if (this.ForeginFolderBillRb.IsChecked == true)
            {
                type = (int)WeightingBillType.Foreign;
            }

            if (this.MixtrueFolderBillRb.IsChecked == true)
            {
                type = (int)WeightingBillType.Mixture;
            }

            if (this.LoadBillRb.IsChecked == true)
            {
                type = (int)WeightingBillType.LoadingBill;
            }
            if (this.UnLoadBillRb.IsChecked == true)
            {
                type = (int)WeightingBillType.UnLoadingBill;
            }
            if (this.ExitFolderBillRb.IsChecked == true)
            {
                type = (int)WeightingBillType.ExitSlip;
            }
            var customizeBill = customizeBillVo.mCustomizeBill;
            var oldId = customizeBillVo.Id;
            customizeBill.id = IdHelper.LongID;
            customizeBill.type = type;
            customizeBill.isUsed = false;
            customizeBill.addTime = DateTime.Now;

            int res = SysCustomizeBillDao.Instance.Insert(customizeBill);


            if (res > 0)
            {
                var msg = "移动成功";
                CommonFunction.AlertInfo(msg);
                this.moveToPopup.IsOpen = false;

                customizeBill.id = oldId;
                SysCustomizeBillDao.Instance.Delete(customizeBill);

                LoadFileItemSource();
            }
            else
            {
                var msg = "移动失败";
                CommonFunction.AlertInfo(msg);
            }
        }

        private void MovePopupCancelBtn_Click(object sender, RoutedEventArgs e)
        {
            this.moveToPopup.IsOpen = false;
        }

        #endregion


        //刷新文本
        private void RefresStaticTextBtn_Click(object sender, RoutedEventArgs e)
        {
            if (mCurrDragUc == null) return;

            if (mCurrDragUc.Name.StartsWith(Constant.StaticTextNamePre))
            {
                //create new static text
                var newStaticText = new DragUc
                {
                    //staticText
                    Name = Constant.StaticTextNamePre + "Uc",
                    LabelTitle = "",
                    BorderBrush = Brushes.Black,
                    BorderThickness = new Thickness(0),
                    TextValue = mCurrDragUc.TextValue,
                    TitleVisibility = Visibility.Collapsed,
                    ColonsVisibility = Visibility.Collapsed
                };
                newStaticText.MouseLeftButtonUp += Draguc_MouseLeftButtonUp;
                double top = (double)mCurrDragUc.GetValue(Canvas.TopProperty);
                double left = (double)mCurrDragUc.GetValue(Canvas.LeftProperty);
                Canvas.SetLeft(newStaticText, left);
                Canvas.SetTop(newStaticText, top);
                newStaticText.SetValueFontSize(mCurrDragUc.GetValueFontSize());
                newStaticText.SetTitleFontSize(mCurrDragUc.GetTitleFontSize());
                newStaticText.ValueFontSize = mCurrDragUc.GetValueFontSize();
                this.mainCanvas.Children.Remove(mCurrDragUc);
                this.mainCanvas.Children.Add(newStaticText);

                mCurrDragUc = null;
            }
        }

        //复制文本
        private void CopyStaticTextBtn_Click(object sender, RoutedEventArgs e)
        {
            if (mCurrDragUc == null) return;

            if (mCurrDragUc.Name.StartsWith(Constant.StaticTextNamePre))
            {
                //create new static text
                var newStaticText = new DragUc()
                {
                    //staticText
                    Name = Constant.StaticTextNamePre + "Uc",
                    LabelTitle = "",
                    BorderBrush = Brushes.Black,
                    BorderThickness = new Thickness(0),
                };
                newStaticText.TextValue = mCurrDragUc.TextValue + " 复制";
                newStaticText.TitleVisibility = Visibility.Collapsed;
                newStaticText.ColonsVisibility = Visibility.Collapsed;
                newStaticText.MouseLeftButtonUp += Draguc_MouseLeftButtonUp;
                double top = (double)mCurrDragUc.GetValue(Canvas.TopProperty);
                double left = (double)mCurrDragUc.GetValue(Canvas.LeftProperty);
                newStaticText.ValueFontSize = mCurrDragUc.GetValueFontSize();
                Canvas.SetLeft(newStaticText, left + 50);
                Canvas.SetTop(newStaticText, top + 50);
                newStaticText.SetValueFontSize(mCurrDragUc.GetValueFontSize());
                newStaticText.SetTitleFontSize(mCurrDragUc.GetTitleFontSize());
                this.mainCanvas.Children.Add(newStaticText);
            }
        }

        /// <summary>
        /// 复制线条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CopyLineBtn_Click(object sender, RoutedEventArgs e)
        {
            if (mCurrLine == null) return;
            if (mCurrLine.Name.Equals(Constant.QrCodeName))
            {
                //this.currDracUiTb.Text = "二维码";
            }
            else if (mCurrLine.Name.Equals(Constant.BarCodeName))
            {
                //this.currDracUiTb.Text = "条形码";
            }
            else
            {
                double w = mCurrLine.Width;
                double h = mCurrLine.Height;
                double top = (double)mCurrLine.GetValue(Canvas.TopProperty);
                double left = (double)mCurrLine.GetValue(Canvas.LeftProperty);

                DragLineUc lineUc;
                if ("Vertical".Equals(mCurrLine.Tag.ToString()))
                {
                    //"垂直";
                    lineUc = CreateLine(false, w, h);
                    lineUc.SetValue(Canvas.TopProperty, top);
                    lineUc.SetValue(Canvas.LeftProperty, left + 20);
                }
                else
                {
                    // "水平";
                    lineUc = CreateLine(true, w, h);
                    lineUc.SetValue(Canvas.TopProperty, top + 50);
                    lineUc.SetValue(Canvas.LeftProperty, left);
                }
                this.mainCanvas.Children.Add(lineUc);
            }

        }

        #region 编辑 二维码码规则

        // Dictionary<String ,Object>  是一个无序的集合，
        //使用哈希表来存储键值对。哈希表通过计算键的哈希码来决定每个键值对在表中的位置
        //键的哈希码没有改变，且没有发生哈希冲突（即多个键被映射到同一个槽），
        //那么新键值对可能会覆盖旧的位置，而不是移动到字典的末尾。

        //SortedDictionary<TKey, TValue> 也不是基于插入顺序的，而是基于键的排序顺序。

        /// <summary>
        /// 选中规则
        /// </summary>
        //private Dictionary<string,string> RuleSTrings = new Dictionary<string, string>();
        /// <summary>
        /// 选中规则的 模拟值
        /// </summary>
        //private Dictionary<string, string> MockVales = new Dictionary<string, string>();


        /// <summary>
        /// 选中 规则(key)的 模拟值（value）
        /// </summary>
        private List<KeyValuePair<string, string>> RuleMockVales = new List<KeyValuePair<string, string>>();


        private bool isPopopSetValue = false;

        private void EditQrRulebtn_Click(object sender, RoutedEventArgs e)
        {
            this.EditQrRulePopup.IsOpen = true;
        }

        private void EditQrRulePopup_Opened(object sender, EventArgs e)
        {
            RuleMockVales.Clear();
            this.QrRulesTb.Text = string.Empty;
            this.MockValueTb.Text = string.Empty;

            var list = this.BillItemSPanel.Children;
            var backs = this.backFieldItemPanel.Children;
            foreach (UIElement item in backs)
            {
                list.Add(item);
            }

            foreach (UIElement item in list)
            {
                if (item is CheckBox cb)
                {
                    string field = cb.Name;
                    string propertyName = StringHelper.UpperCaseFirstLetter(field);

                    CheckBox newCb = new CheckBox()
                    {
                        Name = propertyName + "_QRCB",
                        Content = cb.Content,
                        ToolTip = cb.ToolTip,//mock data 
                        Tag = propertyName,
                        Style = cb.Style,
                        IsChecked = false,
                        Margin = new Thickness(4, 2, 4, 2),
                    };

                    newCb.Checked += QrRuleCb_Checked;
                    newCb.Unchecked += QrRuleCb_Unchecked;

                    this.EditQrBillItemPanel.Children.Add(newCb);
                }
            }

            //  ParseQrContent(currCustomizeBillVo.QrContentVo);
            NewParseQrContent(currCustomizeBillVo?.QrContentVo);

        }


        /// <summary>
        /// 原来的 解析规则
        /// </summary>
        /// <param name="qr"></param>
        private void ParseQrContent(string rules)
        {
            //解析 原来的规则
            //var rules = currCustomizeBillVo?.QrRule ?? "";
            if (rules.Contains("|"))
            {
                RuleMockVales.Clear();

                var cbItems = this.EditQrBillItemPanel.Children.OfType<CheckBox>()?.ToList();
                var items = rules.Split('|');
                foreach (var k in items)
                {
                    var cbItem = cbItems?.Find(i => i.Name == k + "_QRCB");
                    if (cbItem != null)
                    {
                        isPopopSetValue = true;
                        cbItem.IsChecked = true;
                        isPopopSetValue = false;
                        var tooltip = cbItem.ToolTip as string;
                        // 判断是否要转码
                        string val = StringHelper.ContainsChinese(tooltip) ? StringHelper.StringToHexString(tooltip, Encoding.UTF8, false) : tooltip ?? "";
                        RuleMockVales.Add(new KeyValuePair<string, string>(k, val));
                    }
                }
            }
        }

        /// <summary>
        /// 解析规则
        /// </summary>
        /// <param name="contentVo">二维码的规则和内容</param>
        private void NewParseQrContent(QrContentVo? contentVo)
        {
            if (contentVo == null) return;
            string valueStr = "";
            isFirstSetQrContent = true;
            switch (contentVo.QrContentType)
            {
                case QrContentType.Number:
                    valueStr = tempQrcodeValue;
                    this.numberRuleCb.IsChecked = true;
                    this.MockValueTb.Text = valueStr;
                    break;
                case QrContentType.ImageUrl:
                    this.UrlTb.Text = contentVo.Url;
                    this.imgUrlRuleCb.IsChecked = true;
                    valueStr = contentVo.Url;
                    this.MockValueTb.Text = valueStr;
                    break;
                case QrContentType.Variables:
                    this.VariablesRuleCb.IsChecked = true;
                    ParseVariables(contentVo);
                    foreach (var i in RuleMockVales)
                    {
                        valueStr += "|" + i.Value;
                    }
                    valueStr = valueStr.TrimStart('|');
                    this.MockValueTb.Text = valueStr;
                    this.QrRulesTb.Text = contentVo.Variables;
                    break;
                case QrContentType.UrlAndVariables:
                    this.UrlTb.Text += contentVo.Url;
                    this.OtherParamTb.Text = contentVo.OtherParam;
                    this.UrlAndOtherRuleCb.IsChecked = true;
                    ParseVariables(contentVo);
                    foreach (var i in RuleMockVales)
                    {
                        valueStr += "&" + i.Key + "=VALUE";
                    }     
                    valueStr = valueStr.TrimStart('&');
                    string param = contentVo.OtherParam;
                    if (!param.StartsWith('&'))
                    {
                        param = "&" + param;
                    }
                    valueStr = contentVo.Url + "?" + valueStr + param;
                    this.MockValueTb.Text = valueStr;
                    this.QrRulesTb.Text = contentVo.Variables;
                    break;
            }
            isFirstSetQrContent = false;

            ShowPopopQrImage(valueStr);
        }

        /// <summary>
        /// 解析 磅单变量,选中已经设置的项
        /// </summary>
        private void ParseVariables(QrContentVo contentVo)
        {
            RuleMockVales.Clear();
            var cbItems = this.EditQrBillItemPanel.Children.OfType<CheckBox>()?.ToList();
            var items = contentVo.Variables.Split('|');
            foreach (var k in items)
            {
                var cbItem = cbItems?.Find(i => i.Name == k + "_QRCB");
                if (cbItem != null)
                {
                    isPopopSetValue = true;
                    cbItem.IsChecked = true;
                    isPopopSetValue = false;
                    var tooltip = cbItem.ToolTip as string;
                    // 判断是否要转码
                    string val = StringHelper.ContainsChinese(tooltip) ? StringHelper.StringToHexString(tooltip, Encoding.UTF8, false) : tooltip ?? "";
                    RuleMockVales.Add(new KeyValuePair<string, string>(k, val));
                }
            }
        }

        #region Edit Qr Rule CheckBox  Checked Unchecked

        private void QrRuleCb_Checked(object sender, RoutedEventArgs e)
        {
            if (isPopopSetValue) return;
            if (sender is CheckBox cb)
            {
                var k = cb.Tag as string ?? "";
                var tooltip = cb.ToolTip as string;
                string val = StringHelper.ContainsChinese(cb.ToolTip as string) ? StringHelper.StringToHexString(tooltip, Encoding.UTF8, false) : tooltip ?? "";
                var kv = new KeyValuePair<string, string>(k, val);
                if (RuleMockVales.Contains(kv)) { RuleMockVales.Remove(kv); }
                RuleMockVales.Add(kv);

                //设置类型
                var vo = currCustomizeBillVo?.QrContentVo;
                if (vo != null)
                {
                    vo.QrContentType = GetContentType();
                }

                RefreshRulesTb(vo);
                RefreshMockValueTb(vo);
            }
        }


        private void QrRuleCb_Unchecked(object sender, RoutedEventArgs e)
        {
            if (isPopopSetValue) return;
            if (sender is CheckBox cb)
            {
                var k = cb.Tag?.ToString() ?? "Key";
                var tooltip = cb.ToolTip as string;
                string val = (StringHelper.ContainsChinese(cb.ToolTip as string) ? StringHelper.StringToHexString(tooltip, Encoding.UTF8, false) : tooltip) ?? "";
                var kv = new KeyValuePair<string, string>(k, val);
                if (RuleMockVales.Contains(kv))
                {
                    RuleMockVales.Remove(kv);
                }

                //设置类型
                var vo = currCustomizeBillVo?.QrContentVo;
                if (vo != null)
                {
                    vo.QrContentType = GetContentType();
                }

                RefreshRulesTb(vo);
                RefreshMockValueTb(vo);
            }
        }

        private QrContentType GetContentType()
        {
            if (this.numberRuleCb.IsChecked == true)
            {
                return QrContentType.Number;
            }
            else if (this.imgUrlRuleCb.IsChecked == true)
            {
                return QrContentType.ImageUrl;
            }
            else if (this.VariablesRuleCb.IsChecked == true)
            {
                return QrContentType.Variables;
            }
            else if (this.UrlAndOtherRuleCb.IsChecked == true)
            {
                return QrContentType.UrlAndVariables;
            }
            return QrContentType.Number;
        }

        private void RefreshRulesTb(QrContentVo? contentVo)
        {
            if (contentVo == null) return;
            string RuleString = "";
            switch (contentVo.QrContentType)
            {
                case QrContentType.Number:
                    this.QrRulesTb.Text = "Nuber";
                    break;
                case QrContentType.ImageUrl:
                    this.UrlTb.Text = contentVo.Url;
                    this.QrRulesTb.Text = "";
                    break;
                case QrContentType.Variables:
                    foreach (var i in RuleMockVales)
                    {
                        RuleString += "|" + i.Key;
                    }
                    this.QrRulesTb.Text = RuleString.TrimStart('|');
                    break;
                case QrContentType.UrlAndVariables:
                    var varKey = "";
                    foreach (var i in RuleMockVales)
                    {
                        varKey += "&" + i.Key + "=VALUE";
                    }
                    varKey = varKey.TrimStart('&');
                    string param = this.OtherParamTb.Text;
                    if (!param.StartsWith('&'))
                    {
                        param = "&" + param;
                    }
                    RuleString = contentVo.Url + "?" + varKey + param;
                    this.QrRulesTb.Text = RuleString;
                    break;
            }
        }

        private void RefreshMockValueTb(QrContentVo? contentVo)
        {
            string ValueString = "";
            if (contentVo == null) return;
            switch (contentVo.QrContentType)
            {
                case QrContentType.Number:
                    ValueString = tempQrcodeValue;
                    this.MockValueTb.Text = ValueString;
                    break;
                case QrContentType.ImageUrl:
                    ValueString = contentVo.Url;
                    this.MockValueTb.Text = ValueString;
                    this.QrRulesTb.Text = "";
                    break;
                case QrContentType.Variables:
                    foreach (var i in RuleMockVales)
                    {
                        ValueString += "|" + i.Value;
                    }
                    ValueString = ValueString.TrimStart('|');
                    this.MockValueTb.Text = ValueString;
                    var rules = "";
                    foreach (var i in RuleMockVales)
                    {
                        rules += "|" + i.Key;
                    }
                    this.QrRulesTb.Text = rules.TrimStart('|');
                    break;
                case QrContentType.UrlAndVariables:
                    var varKey = "";
                    foreach (var i in RuleMockVales)
                    {
                        varKey += "&" + i.Key + "=VALUE";
                    }
                    varKey = varKey.TrimStart('&');
                    string param = this.OtherParamTb.Text;
                    if (!param.StartsWith('&'))
                    {
                        param = "&" + param;
                    }
                    ValueString = contentVo.Url + "?" + varKey + param;
                    this.MockValueTb.Text = ValueString;
                    var rules2 = "";
                    foreach (var i in RuleMockVales)
                    {
                        rules2 += "|" + i.Key;
                    }
                    this.QrRulesTb.Text = rules2.TrimStart('|');
                    break;
            }

            ShowPopopQrImage(ValueString);
        }


        /// <summary>
        ///  显示样例 二维码
        /// </summary>
        /// <param name="value">二维码内容</param>
        private void ShowPopopQrImage(string value)
        {
            CommonFunction.ShowQrCode(this.QrSimpleImage, value);
        }

        #endregion

        #region 选中后改变
        private void numberRuleCb_Checked(object sender, RoutedEventArgs e)
        {
            this.UrlTb.Visibility = Visibility.Collapsed;
            this.OtherParamTb.Visibility = Visibility.Collapsed;

            ChangedValue();
        }

        private void imgUrlRuleCb_Checked(object sender, RoutedEventArgs e)
        {
            this.UrlTb.Visibility = Visibility.Visible;
            this.OtherParamTb.Visibility = Visibility.Collapsed;
            ChangedValue();
        }

        private void VariablesRuleCb_Checked(object sender, RoutedEventArgs e)
        {
            this.UrlTb.Visibility = Visibility.Collapsed;
            this.OtherParamTb.Visibility = Visibility.Collapsed;

            ChangedValue();
        }

        private void UrlAndOtherRuleCb_Checked(object sender, RoutedEventArgs e)
        {
            this.UrlTb.Visibility = Visibility.Visible;
            this.OtherParamTb.Visibility = Visibility.Visible;

            ChangedValue();
        }

        private void ChangedValue()
        {
            //设置类型
            var vo = currCustomizeBillVo?.QrContentVo;
            if (vo != null)
            {
                vo.QrContentType = GetContentType();
            }

            if (isFirstSetQrContent || this.EditQrRulePopup.IsOpen == false) return;
            RefreshRulesTb(vo);
            RefreshMockValueTb(vo);
        }
        #endregion


        #region LostFocus update
        private void UrlTb_LostFocus(object sender, RoutedEventArgs e)
        {
            if (this.imgUrlRuleCb.IsChecked == true)
            {
                var ValueStr = this.UrlTb.Text;

                ShowPopopQrImage(ValueStr);
            }
            else if (this.imgUrlRuleCb.IsChecked == true || this.UrlAndOtherRuleCb.IsChecked == true)
            {
                var ValueStr = "";

                foreach (var i in RuleMockVales)
                {
                    ValueStr += "&" + i.Key + "=VALUE";
                }

                ValueStr = ValueStr.TrimStart('&');
                string param = this.OtherParamTb.Text;
                ValueStr = this.UrlTb.Text + "?" + ValueStr + "&" + param;

                ShowPopopQrImage(ValueStr);
            }
        }

        private void OtherParamTb_LostFocus(object sender, RoutedEventArgs e)
        {
            if (this.UrlAndOtherRuleCb.IsChecked == true)
            {
                var ValueStr = "";

                foreach (var i in RuleMockVales)
                {
                    ValueStr += "&" + i.Key + "=VALUE";
                }

                ValueStr = ValueStr.TrimStart('&');
                string param = this.OtherParamTb.Text;
                ValueStr = this.UrlTb.Text + "?" + ValueStr + "&" + param;

                ShowPopopQrImage(ValueStr);
            }
        }
        #endregion

        private void EditQrRulePopup_Closed(object sender, EventArgs e)
        {
            var mockStr = this.MockValueTb.Text.Trim();
            RuleMockVales.Clear();
            if (!mockStr.IsNullOrEmpty())
            {
                ShowImageSourceAsync(currImage, Constant.QrCodeName, mockStr);
            }
        }

        private void SaveQrRulePopupBtn_Click(object sender, RoutedEventArgs e)
        {
            CurrQrContentVo = GetCurrQrContentVo();

            this.EditQrRulePopup.IsOpen = false;
        }

        private void QrRulePopupCancelBtn_Click(object sender, RoutedEventArgs e)
        {
            CurrQrContentVo = GetCurrQrContentVo();
            this.EditQrRulePopup.IsOpen = false;
        }


        private QrContentVo GetCurrQrContentVo()
        {
            var varKey = "";
            foreach (var i in RuleMockVales)
            {
                varKey += "|" + i.Key;
            }

            var vo = new QrContentVo()
            {
                Variables = varKey.TrimStart('|') //需要构建
            };

            if (this.numberRuleCb.IsChecked == true)
            {
                vo.QrContentType = QrContentType.Number;
            }
            else if (this.imgUrlRuleCb.IsChecked == true)
            {
                vo.QrContentType = QrContentType.ImageUrl;
            }
            else if (this.VariablesRuleCb.IsChecked == true)
            {
                vo.QrContentType = QrContentType.Variables;
            }
            else if (this.UrlAndOtherRuleCb.IsChecked == true)
            {
                vo.QrContentType = QrContentType.UrlAndVariables;
            }

            vo.Url = this.UrlTb.Text;
            vo.OtherParam = this.OtherParamTb.Text;
            return vo;
        }
        #endregion


        private void ShowImageSourceAsync(Image? image, string name, string content = "")
        {
            if (image == null) return;
            Task.Delay(1000).ContinueWith((t) =>
            {
                this.Dispatcher.Invoke(() =>
                {
                    if (name.Equals(Constant.QrCodeName))
                    {
                        content = content.IsNullOrEmpty() ? tempQrcodeValue : content;
                        CommonFunction.ShowBillNumberQrCode(image, content);
                    }
                    else
                    {
                        content = tempQrcodeValue;
                        CommonFunction.ShowBillNumberBarCode(image, content);
                    }
                });
            });
        }


        /// <summary>
        /// 显示 二维码操作的选项
        /// </summary>
        /// <param name="isShow"></param>
        private void ShowQrOptions(bool isShow = false)
        {
            if (isShow)
            {
                this.QrRuleWp.Visibility = Visibility.Visible;

                BindingValue();
            }
            else
            {
                this.QrRuleWp.Visibility = Visibility.Collapsed;
            }

        }
        private void BindingValue()
        {
            if (isBindingValue) return;
            isBindingValue = true;
            if (currCustomizeBillVo == null) return;

            if (currCustomizeBillVo.QrContentVo == null)
            {
                currCustomizeBillVo.QrContentVo = new QrContentVo()
                {
                    QrContentType = QrContentType.Number,
                };
            }

            switch (currCustomizeBillVo.QrContentVo.QrContentType)
            {
                case QrContentType.Number:
                    this.numberRuleCb.IsChecked = true;
                    break;
                case QrContentType.ImageUrl:
                    this.imgUrlRuleCb.IsChecked = true;
                    this.UrlTb.Text = currCustomizeBillVo.QrContentVo.Url;
                    break;
                case QrContentType.Variables:
                    this.VariablesRuleCb.IsChecked = true;                 
                    break;
                case QrContentType.UrlAndVariables:
                    this.UrlAndOtherRuleCb.IsChecked = true;                  
                    break;
            }
            isBindingValue = false;
        }

    }
}
